using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Net;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Threading;
using System.IO;

[assembly: CLSCompliant(true)]
namespace Wandor
{
	public struct NewLookupPacket
	{
		public string guid;
		public string sfrom;
		public string sto;
		public uint multiple;
	}
	public partial class MainWindow : Form
	{
		private const string UrlPattern = "http://maps.google.hu/maps?f=d&source=s_d&saddr={from}&daddr={to}&hl=hu";
		public MainWindow()
		{
			InitializeComponent();
		}
		
		private static void Main(string[] args)
		{
			using(var window = new MainWindow())
			{
				Application.Run(window);
			}
		}
		
		public void calculateButton_Click(object sender, EventArgs args)
		{
			if(string.IsNullOrEmpty(fromBox.Text) || string.IsNullOrEmpty(toBox.Text))
			{
				MessageBox.Show("A mezők nincsenek megfelelően kitöltve.", "Hiba!", MessageBoxButtons.OK);
				return;
			}
			
			var url = new Uri(UrlPattern.Replace("{from}", HttpUtility.UrlEncode(fromBox.Text)).Replace("{to}", HttpUtility.UrlEncode(toBox.Text)));
			
			var client = new WebClient();
			client.Encoding = Encoding.UTF8;
			string data = client.DownloadString(url);
			client.Dispose();
			
			var getDistanceRegex = new Regex(@",distance:.(?<distance>\S+)\s*(?<unit>\S*).,time");
			
			if(!getDistanceRegex.IsMatch(data))
			{
				MessageBox.Show("Az út a két város között nem található vagy a térkép-adatbázis struktúra megváltozott! Kérem szóljon a fejlesztőknek!", "Hiba!", MessageBoxButtons.OK);
				return;
			}
			
			var matches = getDistanceRegex.Matches(data);
			
#if SERVER_COMMUNICATION
			
			var packet = new NewLookupPacket();
			packet.guid = (string)(Environment.UserName + "@" + Environment.MachineName);
			packet.sfrom = fromBox.Text;
			packet.sto = toBox.Text;
			packet.multiple = (uint)(matches.Count - 1);
			

			PacketManager.SendPacket(Opcode.CMSG_NEW_LOOKUP, packet, "127.0.0.1", 3366);
					
#endif		
			
		
			new FinishWindow(matches, url).ShowDialog();
		}
		
		
	}

#if SERVER_COMMUNICATION
	public static class PacketManager
	{
		public static void SendPacket(Opcode opcode, NewLookupPacket packet, string host, int port)
		{
			var client = new TcpClient();
			
			client.Connect(host, port);
			
			Thread.Sleep(500);
			
			if(!client.Connected)
			{
				client.Close(); // dispose aswell
				return;
			}
			
			using(var writer = new BinaryWriter(client.GetStream()))
			{
				if(opcode == Opcode.CMSG_NEW_LOOKUP)
				{
					try
					{
						
						
						var guid_s = packet.guid;
						var sfrom = packet.sfrom;
						var sto = packet.sto;
						var more_choices = packet.multiple;
						
						
						
						
						// forward to server
						writer.Write((int)Opcode.CMSG_NEW_LOOKUP); // opcode
						writer.Write(guid_s);
						writer.Write(sfrom);
						writer.Write(sto);
						writer.Write(more_choices);
						
						
					}
					catch(Exception x)
					{
						MessageBox.Show(x.Message + Environment.NewLine + x.InnerException + Environment.NewLine + "Help: " + x.HelpLink + Environment.NewLine + Environment.NewLine + x.StackTrace);
					}
				}
			}
			
			client.Close();
			
		}
	}
#endif
}
